package com.jplus.core.plugin.scheduling.cron;

import java.util.Date;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public abstract class ScheduledTask extends Thread {
	public Logger log = LoggerFactory.getLogger(ScheduledTask.class);
	private CronKit ck;

	public ScheduledTask(String cron) {
		this.ck = new CronKit(cron);
	}

	@Override
	public void run() {
		while (true) {
			try {
				Date now = new Date();
				Date next = ck.next();
				log.info("[Task]:Next execution time = " + next);
				if (next.after(now)) {
					long wait = next.getTime() - now.getTime();
					Thread.sleep(wait);
					invokeMethod();
				} else {
					Thread.sleep(1000);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	public abstract void invokeMethod();

	public static void main(String[] args) {
		new ScheduledTask("0/5 * * * * ? ") {
			@Override
			public void invokeMethod() {
				System.out.println(">>执行任务。。。");
			}
		}.start();
	}
}
